package com.wangy.database.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.wangy.database.bean.JdbcInfo;
import com.wangy.utils.ConfigProperties;

public class DBUtil {

	public static final String JDBC_URL = "jdbcUrl";
	public static final String USERNAME = "username";
	public static final String PASSWORD = "password";
	public static final String DRIVER_NAME = "dirverName";

	public static void close(Connection connection) {
		try {
			if (connection != null) {
				connection.close();
				connection = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static void close(Statement statement) {
		try {
			if (statement != null) {
				statement.close();
				statement = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static void close(ResultSet resultSet) {
		try {
			if (resultSet != null) {
				resultSet.close();
				resultSet = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static void close(Statement statement, Connection connection) {
		try {
			if (statement != null) {
				statement.close();
				statement = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (connection != null) {
					connection.close();
					connection = null;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static void close(ResultSet resultSet, Statement statement,
			Connection connection) {
		try {
			if (resultSet != null) {
				resultSet.close();
				resultSet = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (statement != null) {
					statement.close();
					statement = null;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				try {
					if (connection != null) {
						connection.close();
						connection = null;
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static void commit(Connection connection) {
		try {
			connection.commit();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static void rollback(Connection connection) {
		try {
			connection.rollback();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static JdbcInfo getJdbcInfo(ConfigProperties configProperties) {
		JdbcInfo jdbcInfo = new JdbcInfo();
		jdbcInfo.setUrl(configProperties.getValue(JDBC_URL));
		jdbcInfo.setDriverName(configProperties.getProperty(DRIVER_NAME));
		jdbcInfo.setUsername(configProperties.getProperty(USERNAME));
		jdbcInfo.setPassword(configProperties.getProperty(PASSWORD));
		return jdbcInfo;
	}

}
